package com.gxitsky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxitsky.entity.DoubleColorBall;
import com.gxitsky.exception.BusinessException;
import com.gxitsky.mapper.DoubleColorBallMapper;
import com.gxitsky.service.DoubleColorBallService;
import com.gxitsky.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author gxing
 * @desc 双色球
 * @date 2022/11/30
 */
@Slf4j
@Service
public class DoubleColorBallServiceImpl implements DoubleColorBallService {

    public static String DoubleColorUrl = "http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueStart={start}&issueEnd={end}";
    //33选6 不重复, 16选1 = 12,759,183,360组合
    public static List<Integer> RED_LIST = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33));
    public static List<Integer> BLUE_LIST = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DoubleColorBallMapper doubleColorBallMapper;

    /**
     * @desc 同步最新
     * @author gxing
     * @date 2022/11/30
     */
    @Override
    public void syncLast() {
        DoubleColorBall doubleColorBall = queryLastOne();
        Integer nextCode = doubleColorBall.getCode() + 1;
        String date = doubleColorBall.getDate();
        Date lastDate = DateUtil.parseDate(date, DateUtil.PATTERN_YMD_NORMAL);
        String lastYear = DateUtil.format(lastDate, DateUtil.PATTERN_YYYY_NORMAL);
        String currentYear = LocalDate.now().format(DateTimeFormatter.ofPattern(DateUtil.PATTERN_YYYY_NORMAL));
        if (!lastYear.equals(currentYear)) {
            nextCode = Integer.valueOf(currentYear + "001");
        }
        String nextData = getNextOne(nextCode);
        List<DoubleColorBall> ballList = dataParse(nextData);
        saveData(ballList);
    }

    /**
     * @param count 多少组
     * @desc 生成随机数字
     * @author gxing
     * @date 2022/11/30
     */
    @Override
    public List<String> random(Integer count) {
        List<String> resultList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            String result = redBlueBall();
            resultList.add(result);
        }
        return resultList;
    }

    public String redBlueBall() {
        List<Integer> resultList = new ArrayList<>();
        Random random = new Random();
        //红球 33选6,不重复
        do {
            int redIndex = random.nextInt(RED_LIST.size());
            Integer integer = RED_LIST.get(redIndex);
            if (!resultList.contains(integer)) {
                resultList.add(integer);
            }
        } while (resultList.size() < 6);
        Collections.sort(resultList);
        // 蓝球 16选1
        int blueIndex = random.nextInt(BLUE_LIST.size());
        Integer blue = BLUE_LIST.get(blueIndex);

        // 结果
        StringBuilder sb = new StringBuilder();
        resultList.forEach(e -> sb.append(String.format("%02d", e)).append(","));
        StringBuilder sb1 = sb.replace(sb.length() - 1, sb.length(), "");
        sb1.append("-----").append(String.format("%02d", blue));
        return sb1.toString();
    }

    /**
     * @desc 查最后一条
     * @author gxing
     * @date 2022/11/30 9:20
     */
    public DoubleColorBall queryLastOne() {
        LambdaQueryWrapper<DoubleColorBall> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(DoubleColorBall::getCode).last("limit 1");
        DoubleColorBall doubleColorBall = doubleColorBallMapper.selectOne(queryWrapper);
        return doubleColorBall;
    }

    private String getNextOne(Integer nextCode) {
        String url1 = DoubleColorUrl.replace("{start}", String.valueOf(nextCode)).replace("{end}", String.valueOf(nextCode));
        String data = restTemplate.getForObject(url1, String.class);
        return data;
    }

    private List<DoubleColorBall> dataParse(String resultStr) {
        JSONObject response = JSON.parseObject(resultStr, JSONObject.class);
        int state = response.getInteger("state");
        if (state != 0) {
            log.warn("----->获取数据异常:{}", JSON.toJSONString(response));
            String errorMsg = response.getString("message");
            throw new BusinessException(errorMsg);
        }
        JSONArray jsonArray = (JSONArray) response.get("result");
        List<DoubleColorBall> list = new ArrayList<>();
        for (Object o : jsonArray) {
            JSONObject r = (JSONObject) o;
            String code = r.getString("code");
            String date = r.getString("date");
            String red = r.getString("red");
            String blue = r.getString("blue");
            String week = r.getString("week");
            DoubleColorBall doubleColorBall = new DoubleColorBall();
            doubleColorBall.setCode(Integer.valueOf(code));
            doubleColorBall.setWeek(week);
            doubleColorBall.setRed(red);
            doubleColorBall.setBlue1(Integer.valueOf(blue));
            int index = date.indexOf("(");
            date = date.substring(0, index);
            doubleColorBall.setDate(date);

            String[] reds = red.split(",");
            for (int i = 0; i < reds.length; i++) {
                doubleColorBall.setRed1(Integer.valueOf(reds[0]));
                doubleColorBall.setRed2(Integer.valueOf(reds[1]));
                doubleColorBall.setRed3(Integer.valueOf(reds[2]));
                doubleColorBall.setRed4(Integer.valueOf(reds[3]));
                doubleColorBall.setRed5(Integer.valueOf(reds[4]));
                doubleColorBall.setRed6(Integer.valueOf(reds[5]));
            }
            list.add(doubleColorBall);
        }
        return list;
    }

    public void saveData(List<DoubleColorBall> colorBallList) {
        List<DoubleColorBall> list1 = colorBallList.stream().sorted(new Comparator<DoubleColorBall>() {
            @Override
            public int compare(DoubleColorBall o1, DoubleColorBall o2) {
                return o1.getCode().compareTo(o2.getCode());
            }
        }).collect(Collectors.toList());
        list1.forEach(e -> {
            doubleColorBallMapper.insert(e);
        });
    }
}
